package oas.web;

import com.sun.corba.se.spi.orbutil.threadpool.Work;
import oas.db.AttendanceRepository;
import oas.db.LeaveRepository;

import oas.db.UserRepository;
import oas.db.WorkcellRepository;
import oas.domain.Attendance;
import oas.domain.User;

import oas.domain.Workcell;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.jboss.logging.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工控制类
 *
 * @author ZhangC
 * @version 1.2.0
 */
@Controller
@RequestMapping("/employee")
public class EmployeeController {
    private final static Log log = LogFactory.getLog(EmployeeController.class);
    //注入资源
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AttendanceRepository attendanceRepository;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 员工管理主页面
     *
     * @param pageNo   当前页码
     * @param pageSize 页面大小
     * @param session  会话session
     * @param model    前端model
     * @return 员工管理页面
     */
    @RequestMapping(method = RequestMethod.GET)
    public String employees(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                            HttpSession session,
                            Model model) {

        User employee = (User) session.getAttribute("user");
        model.addAttribute("paginationSupport", userRepository.findEmployeePage(employee, pageNo, pageSize));
        return "employees";
    }

    /**
     * 提交添加员工
     *
     * @param username   员工用户名
     * @param password   员工密码
     * @param fullName   员工全面
     * @param email      员工邮箱
     * @param phoneNo    员工电话
     * @param age        员工年龄
     * @param workcellId 员工部门id
     * @param gender     员工性别
     * @param model      model
     * @return 员工信息详情页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String processAddEmployee(@RequestParam("username") String username, @RequestParam("password") String password,
                                     @RequestParam("fullName") String fullName, @RequestParam("email") String email,
                                     @RequestParam("phoneNo") String phoneNo, @RequestParam("age") String age,
                                     @RequestParam("workcell") String workcellId, @RequestParam("gender") String gender,
                                     @RequestParam("role") String role, Model model) {
        Workcell workcell = new Workcell(Long.parseLong(workcellId), null, false, null);
        User employee = new User(null, username, fullName, workcell, gender, email, phoneNo, Integer.parseInt(age), role, true);

        employee = userRepository.addEmployee(employee, password);
        model.addAttribute("employee", employee);
        return "employeeDetails";
    }

    /**
     * 根据指定id删除员工
     *
     * @param employeeId 员工id
     * @return 员工管理页面
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public String deleteEmployee(@PathVariable("id") Long employeeId) {
        userRepository.deleteEmployeeByID(employeeId);
        return "redirect:/employee";
    }

    /**
     * 进入更新员工信息页面
     *
     * @param model model
     * @return 更新员工信息页面
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String updateEmployee(@PathVariable("id") String id, Model model) {
        User employee = userRepository.findById(Integer.parseInt(id));
        model.addAttribute("employee", employee);
        Map<String, String> genderList = new HashMap<String, String>();
        genderList.put("Male", "Male");
        genderList.put("Female", "Female");
        model.addAttribute("genderList", genderList);
        return "updateEmployeeForm";
    }

    /**
     * 提交更新员工信息
     *
     * @param employee 员工部分信息
     * @param id       员工id
     * @param model    model
     * @return 修改成功，返回员工详情信息
     */
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public String processUpdate(User employee, @PathVariable("id") String id, Model model) {
        employee.setId(Long.parseLong(id));
        employee = userRepository.updateEmployee(employee);
        model.addAttribute(employee);
        return "redirect:/employee/details/{id}";
    }

    /**
     * 查看某一员工详情信息
     *
     * @param userID 员工id
     * @param model  model
     * @return 员工详情页面
     */
    @RequestMapping(value = "/details/{userID}", method = RequestMethod.GET)
    public String userDetail(@PathVariable("userID") long userID, Model model) {
        User employee = userRepository.findById((int) userID);
        model.addAttribute("employee", employee);
        return "employeeDetails";
    }

    /**
     * 查询用户考勤记录
     *
     * @param pageNo   起始页码
     * @param pageSize 页面大小
     * @param start    起始日期
     * @param end      截止日期
     * @param userName 用户名
     * @param model    前端视图
     * @return jsp页面名称
     */
    @RequestMapping(value = "/attendances", method = RequestMethod.GET)
    public String userAttendances(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
                                  @RequestParam(value = "startDate", defaultValue = "null") String start,
                                  @RequestParam(value = "endDate", defaultValue = "null") String end,
                                  @RequestParam(value = "userName", defaultValue = "null") String userName,
                                  Model model) {

        Logger.getLogger("oas").debug(userName + ": " + start + ", " + end);
        Date startDate = null, endDate = null;

        //判断用户名参数是否为空
        if ("null".equals(userName)) {
            userName = null;
            try {
                if ("null".equals(start) && "null".equals(end)) {
                    //既没有起始日期有没有截止日期，则返回所有考勤记录

                    startDate = simpleDateFormat.parse("2000-01-01");
                    endDate = new Date();

                } else if ("null".equals(start)) {
                    //只有截止日期，返回截止日期前所有的考勤记录

                    startDate = simpleDateFormat.parse("2000-01-01");
                    endDate = simpleDateFormat.parse(end);
                    if (endDate.before(simpleDateFormat.parse("2000-01-01"))) {
                        model.addAttribute("warningMsg", "请输入不早于2000年1月1日的截止日期");
                        return "userAttendances";
                    }
                    model.addAttribute("initEndDate", end);

                } else if ("null".equals(end)) {
                    //只有起始日期，返回起始日期至今的所有考勤记录

                    startDate = simpleDateFormat.parse(start);
                    endDate = new Date();
                    if (startDate.after(new Date())) {
                        model.addAttribute("warningMsg", "请输入不晚于今天的起始日期日期");
                        return "userAttendances";
                    }
                    model.addAttribute("initStartDate", start);

                } else {

                    startDate = simpleDateFormat.parse(start);
                    endDate = simpleDateFormat.parse(end);
                    if (startDate.after(endDate)) {
                        model.addAttribute("warningMsg", "请输入不晚于今天的起始日期日期");
                        return "userAttendances";
                    }
                    model.addAttribute("initEndDate", end);
                    model.addAttribute("initStartDate", start);

                }
            } catch (ParseException pe) {
                //若请求参数的时间不符合yyyy-MM-dd格式返回提示信息
                model.addAttribute("errMsg", "请输入正确格式的时间！如2020-01-01");
                return "userAttendances";
            }

            PaginationSupport<Attendance> ps = attendanceRepository.findUsersAttendancesPage(pageNo, pageSize, userName, startDate, endDate);
            model.addAttribute("paginationSupport", ps);
            model.addAttribute("okMsg", "查询成功！");
            return "userAttendances";
        }

        //将所查询用户用户名加入model中
        model.addAttribute("initUserName", userName);

        try {
            if ("null".equals(start) && "null".equals(end)) {
                //既没有起始日期有没有截止日期，则返回所有考勤记录

                startDate = simpleDateFormat.parse("2000-01-01");
                endDate = new Date();

            } else if ("null".equals(start)) {
                //只有截止日期，返回截止日期前所有的考勤记录

                startDate = simpleDateFormat.parse("2000-01-01");
                endDate = simpleDateFormat.parse(end);
                if (endDate.before(simpleDateFormat.parse("2000-01-01"))) {
                    model.addAttribute("warningMsg", "请输入不早于2000年1月1日的截止日期");
                    return "userAttendances";
                }
                model.addAttribute("initEndDate", end);

            } else if ("null".equals(end)) {
                //只有起始日期，返回起始日期至今的所有考勤记录

                startDate = simpleDateFormat.parse(start);
                endDate = new Date();
                if (startDate.after(new Date())) {
                    model.addAttribute("warningMsg", "请输入不晚于今天的起始日期日期");
                    return "userAttendances";
                }
                model.addAttribute("initStartDate", start);

            } else {

                startDate = simpleDateFormat.parse(start);
                endDate = simpleDateFormat.parse(end);
                if (startDate.after(endDate)) {
                    model.addAttribute("warningMsg", "请输入不晚于今天的起始日期日期");
                    return "userAttendances";
                }
                model.addAttribute("initEndDate", end);
                model.addAttribute("initStartDate", start);

            }
        } catch (ParseException pe) {
            //若请求参数的时间不符合yyyy-MM-dd格式返回提示信息
            model.addAttribute("errMsg", "请输入正确格式的时间！如2020-01-01");
            return "userAttendances";
        }

        PaginationSupport<Attendance> ps = attendanceRepository.findUsersAttendancesPage(pageNo, pageSize, userName, startDate, endDate);
        model.addAttribute("paginationSupport", ps);
        model.addAttribute("okMsg", "查询成功！");
        return "userAttendances";
    }

}
